package org.summer.netty;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

@Slf4j
public class PacketSplicing {
    public static char LF = '\n';

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put("Hello world\nI am mk\nHow".getBytes(StandardCharsets.UTF_8));
        split(buffer);
        buffer.put(" are you\n".getBytes(StandardCharsets.UTF_8));
        split(buffer);
        log.info("end ......");
    }

    public static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == LF) {
                int len = i + 1 - source.position();
                ByteBuffer to = ByteBuffer.allocate(len);
                copyDiscardLF(source, len, to);
                byteBuffPrint(to);
            }
        }
        source.compact();
    }

    public static void copy(ByteBuffer source, int len, ByteBuffer to) {
        for (int i = 0; i < len; i++) {
            to.put(source.get());
        }
    }

    public static void copyDiscardLF(ByteBuffer source, int len, ByteBuffer to) {
        // len-1  no copy 'lf' ready discard lf byte
        for (int i = 0; i < len - 1; i++) {
            to.put(source.get());
        }
        // discard lf
        source.get();
    }

    public static String byteBuffPrint(ByteBuffer source) {
        source.flip();
        String data = StandardCharsets.UTF_8.decode(source).toString();
        log.info("buff data -> [{}]", data);
        return data;
    }

    public static String getByteBuffData(ByteBuffer source) {
        source.flip();
        return StandardCharsets.UTF_8.decode(source).toString();
    }
}
